package com.aryankh.controller;

import com.aryankh.entity.KhLoginUser;
import com.aryankh.entity.KhUser;
import com.aryankh.service.KhUserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version 1.0
 * @Author AryanKH
 * @Date 2022/5/28 17:47
 * @Default
 */
@Slf4j
@RestController
public class IndexController {
    @Resource
    private KhUserService userService;

    @PostMapping("login")
    public ResponseEntity<KhLoginUser> login(@RequestBody @Validated KhUser khUser,
                                             BindingResult bindingResult) {
        // 处理不合法的数据
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        allErrors.forEach(error -> {
            log.error("登录时用户校验失败 {}", error.getDefaultMessage());
        });

        if (allErrors.size() > 0) {
            return ResponseEntity.status(500).build();
        }

        //2. 执行登录逻辑
        KhLoginUser khLoginUser = null;
        try {
            khLoginUser = userService.login(khUser.getUserName(), khUser.getPassword());
        } catch (JsonProcessingException e) {
            return ResponseEntity.status(500).build();
        }
        return ResponseEntity.ok().body(khLoginUser);
    }

    @GetMapping("logout")
    public ResponseEntity<String> logout() {

        try {
           userService.logout();
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
        return ResponseEntity.ok().body("退出成功");
    }
}
